#include "QRcodeImage.h"

#include <QPainter>

QRcodeImage::QRcodeImage(const QString& information, int version) {
  QRcode* qrcode = QRcode_encodeString(information.toStdString().c_str(),
                                       version, QR_ECLEVEL_H, QR_MODE_8, 1);

  if (!qrcode) return;

  int width = qrcode->width;

  m_image = new QImage(width + 2, width + 2, QImage::Format_ARGB32);
  QPainter painter(m_image);
  QColor background(Qt::white);
  painter.setBrush(background);
  painter.setPen(Qt::NoPen);
  painter.drawRect(0, 0, width + 2, width + 2);

  QColor foreground(Qt::black);
  painter.setBrush(foreground);
  for (int y = 0; y < width; y++) {
    for (int x = 0; x < width; x++) {
      unsigned char character = qrcode->data[y * width + x];
      if (character & 0x01) {
        QRect rect(x + 1, y + 1, 1, 1);
        painter.drawRects(&rect, 1);
      }
    }
  }
}

QRcodeImage::~QRcodeImage() { delete m_image; }
